package com.wf.smartcomm.server.admin.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.json.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.cloopen.rest.sdk.CCPRestSDK;
import com.google.gson.Gson;
import com.opensymphony.xwork2.ModelDriven;
import com.wf.smartcomm.server.bean.House;
import com.wf.smartcomm.server.bean.UnitMachine;
import com.wf.smartcomm.server.bean.User;
import com.wf.smartcomm.server.bean.Village;
import com.wf.smartcomm.server.model.PushMessage;
import com.wf.smartcomm.server.model.UnlockCode;
import com.wf.smartcomm.server.push.Pusher;
import com.wf.smartcomm.server.response.ResponseCode;
import com.wf.smartcomm.server.service.HouseService;
import com.wf.smartcomm.server.service.UnitMachService;
import com.wf.smartcomm.server.service.UserService;
import com.wf.smartcomm.server.service.VillageService;
import com.wf.smartcomm.server.util.ConstantUtils;
import com.wf.smartcomm.server.util.IdUtils;
import com.wf.smartcomm.server.util.PushUtils;

@Controller
@Scope("prototype")
public class ManagerAction extends BaseAction implements ModelDriven<User>{
	
	private User user = new User();
	
	@Resource
	private VillageService villageServiceImpl;
	
	@Resource
	private UserService userServiceImpl;
	
	@Resource
	private HouseService houseServiceImpl;
	
	@Resource
	private UnitMachService unitMachServiceImpl;
	
	public String addUser() throws Exception{
		villageServiceImpl.list(page);
		request.setAttribute("villages", page.getDataList());
		return "add";
	}
	
	public String addCenter()throws Exception{
		villageServiceImpl.list(page);
		request.setAttribute("villages", page.getDataList());
		return "addCenter";
	}
	
	public String updateUnit() throws Exception{
		villageServiceImpl.list(page);
		request.setAttribute("villages", page.getDataList());
		return "success";
	}
	
	public String updateClient() throws Exception{
		return updateUnit();
	}
	
	public String updateCenter() throws Exception{
		return updateUnit();
	}
	
	public void saveUser() throws IOException{
		User mUser = userServiceImpl.getUserByUsername(user.getUsername());
		if (mUser != null) {
			printJsonData(101);
			return;
		}
		String vid = request.getParameter("vid");
		user.setObjectId(IdUtils.uuid());
		user.setPushId(IdUtils.uuid16());
		user.setCreatedAt(String.valueOf(System.currentTimeMillis()));
		user.setUpdateAt(user.getCreatedAt());
		user.setIsUnReg("0");
		user.setDeviceType(ConstantUtils.DEVICE_TYPE_UNKNOW);
		user.setLoginVillage(new Village(vid));
		user.setType(ConstantUtils.USER_TYPE_PROPERTY);
		userServiceImpl.registe(user);
		printJsonData(200);
	}
	
	public void saveCenter() throws Exception{
		User mUser = userServiceImpl.getUserByUsername(user.getUsername());
		if (mUser != null) {
			printJsonData(101);
			return;
		}
		String vid = request.getParameter("vid");
		user.setObjectId(IdUtils.uuid());
		user.setPushId(IdUtils.uuid16());
		user.setCreatedAt(String.valueOf(System.currentTimeMillis()));
		user.setUpdateAt(user.getCreatedAt());
		user.setIsUnReg("0");
		user.setPassword(IdUtils.MD5(user.getPassword()));
		user.setDeviceType(ConstantUtils.DEVICE_TYPE_UNKNOW);
		user.setLoginVillage(new Village(vid));
		user.setType(ConstantUtils.USER_TYPE_CENTER);
		user.setIsCenterUser(1);
		userServiceImpl.registe(user);
		HashMap<String, Object> result = null;
		CCPRestSDK restAPI = new CCPRestSDK();
		if (PushUtils.isDevEnv) {
			restAPI.init("sandboxapp.cloopen.com", "8883");
			restAPI.setAccount("8a48b551516c09cd01516c36b1cf00dd", "a989200a4e29483cb3e5d6107ae9fdd0");
			restAPI.setAppId("aaf98f89516bf50b015180a2d42a2875");
		} else {
			restAPI.init(PushUtils.pushConfig.getProperty("CloudAddress"), PushUtils.pushConfig.getProperty("CloudPort"));// 初始化服务器地址和端口，格式如下，服务器地址不需要写https://
			restAPI.setAccount(PushUtils.pushConfig.getProperty("CloudMainAccount"), PushUtils.pushConfig.getProperty("CloudMainToken"));// 初始化主帐号和主帐号TOKEN
			restAPI.setAppId(PushUtils.pushConfig.getProperty("CloudAppId"));// 初始化应用ID
		}
		result = restAPI.createSubAccount(user.getObjectId());
		if("000000".equals(result.get("statusCode"))){
			//正常返回输出data包体信息（map）
			HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
			List<HashMap<String,Object>> object =  (List<HashMap<String,Object>>) data.get("SubAccount");
			for (HashMap<String, Object> hashMap : object) {
				if (hashMap.containsKey("subAccountSid")) {
					user.setSubAccountSid(hashMap.get("subAccountSid").toString());
				}
				if (hashMap.containsKey("voipAccount")) {
					user.setVoipAccount(hashMap.get("voipAccount").toString());
				}
				if (hashMap.containsKey("voipPwd")) {
					user.setVoipPwd(hashMap.get("voipPwd").toString());
				}
				if (hashMap.containsKey("subToken")) {
					user.setSubToken(hashMap.get("subToken").toString());
				}
			}
			userServiceImpl.initVoipInfo(user);
		}else{
			//异常返回输出错误码和错误信息
			System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
			userServiceImpl.realDel(user);
		}
		printJsonData(200);
	}
	
	public void deleteUser() throws Exception{
		userServiceImpl.deleteUser(user);
		printJsonData(200);
	}
	
	public void listVillage() throws Exception {
		String aoData = request.getParameter("aoData");
		String sEcho = "";
		String iDisplayStart = "";
		String iDisplayLength = "";
		String sSearch = "";
		
		JSONObject jo = new JSONObject(aoData);
		sEcho = jo.getString("sEcho");
		iDisplayStart = jo.getString("iDisplayStart");
		iDisplayLength = jo.getString("iDisplayLength");
		sSearch = jo.getString("sSearch");
		
		page.setBeginIndex(Integer.parseInt(iDisplayStart));
		page.setPageSize(Integer.parseInt(iDisplayLength));
		villageServiceImpl.listToAdmin(page);
		
		int  initEcho = Integer.parseInt(sEcho)+1;
		int count = page.getTotalCount();
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("iTotalRecords", count);
		dataMap.put("sEcho",initEcho);
		dataMap.put("iTotalDisplayRecords", count);
		dataMap.put("aaData", page.getDataList());
		printJsonData(outGson.toJson(dataMap));
	}
	
	public String editHouse() throws Exception{
		String houseId = request.getParameter("houseId");
		House house = houseServiceImpl.getById(houseId);
		request.setAttribute("house", house);
		return "edit";
	}
	
	public void setPassword()throws Exception{
		String hid = request.getParameter("houseId");
		String umpwd = request.getParameter("password");
		House house = houseServiceImpl.getById(hid);
		house.setUnitPassword(umpwd);
		houseServiceImpl.update(house);
		UnlockCode code = new UnlockCode();
		code.setId(hid);
		code.setCode(umpwd);
		Pusher pusher = PushUtils.getInstance();
		PushMessage msg = new PushMessage();
		msg.setPushType(ConstantUtils.PUSH_TYPE_SET_UMPWD);
		msg.setData(code);
		unitMachServiceImpl.listByHid(hid, page);
		List<UnitMachine> ums = (List<UnitMachine>) page.getDataList();
		for (UnitMachine um : ums) {
			pusher.push0x20Message(um.getPushId().getBytes(), new Gson().toJson(msg).getBytes());
		}
		pusher.close();
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		printJsonData(new Gson().toJson(map));
	}
	
	public void setReceiver()throws Exception{
		HashMap<String, Object> map = new HashMap<String, Object>();
		String hid = request.getParameter("houseId");
		String voipNumber = request.getParameter("receiver");
		House house = houseServiceImpl.getById(hid);
		house.setVoipPhoneNumber(voipNumber);
		houseServiceImpl.update(house);
		map.put("code", ResponseCode.OK);
		printJsonData(new Gson().toJson(map));
	}
	
	@Override
	public User getModel() {
		return user;
	}
}
